package com.yang.demo.examples;

import com.yang.demo.client.RestClient;
import com.yang.demo.config.ConfigManager;
import com.yang.demo.model.HttpResponse;
import com.yang.demo.model.User;
import com.yang.demo.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * RestClient使用示例
 * 展示各种HTTP请求的用法
 */
@Slf4j
public class RestClientDemo {

    public static void main(String[] args) {
        try {
            // 运行所有示例
            runAllExamples();
        } catch (Exception e) {
            log.error("示例运行失败", e);
        }
    }

    /**
     * 运行所有示例
     */
    public static void runAllExamples() {
        System.out.println("=== RestClient Demo 开始 ===\n");

        // 1. 配置示例
        configExample();

        // 2. 基本GET请求示例
        basicGetExample();

        // 3. GET请求解析对象示例
        getObjectExample();

        // 4. GET请求解析列表示例
        getListExample();

        // 5. POST请求示例
        postExample();

        // 6. PUT请求示例
        putExample();

        // 7. DELETE请求示例
        deleteExample();

        // 8. 自定义请求头示例
        customHeadersExample();

        // 9. 错误处理示例
        errorHandlingExample();

        // 10. JSON工具类示例
        jsonUtilsExample();

        System.out.println("\n=== RestClient Demo 结束 ===");
    }

    /**
     * 配置示例
     */
    public static void configExample() {
        System.out.println("1. 配置示例");
        System.out.println("=" + "=".repeat(50));

        ConfigManager config = ConfigManager.getInstance();

        System.out.println("连接超时: " + config.getConnectTimeout() + "ms");
        System.out.println("Socket超时: " + config.getSocketTimeout() + "ms");
        System.out.println("连接请求超时: " + config.getConnectionRequestTimeout() + "ms");
        System.out.println("总体超时: " + config.getTotalTimeout() + "ms");
        System.out.println("代理启用: " + config.isProxyEnabled());
        System.out.println("连接池最大连接数: " + config.getConnectionPoolMaxTotal());
        System.out.println("默认字符集: " + config.getDefaultCharset());
        System.out.println("用户代理: " + config.getUserAgent());
        System.out.println("日志启用: " + config.isLoggingEnabled());
        System.out.println();
    }

    /**
     * 基本GET请求示例
     */
    public static void basicGetExample() {
        System.out.println("2. 基本GET请求示例");
        System.out.println("=" + "=".repeat(50));

        RestClient client = new RestClient();

        try {
            // 使用一个公共的测试API
            String url = "https://httpbin.org/get";
            HttpResponse<String> response = client.get(url);

            System.out.println("请求URL: " + url);
            System.out.println("状态码: " + response.getStatusCode());
            System.out.println("响应消息: " + response.getMessage());
            System.out.println("响应时间: " + response.getResponseTime() + "ms");
            System.out.println("Content-Type: " + response.getContentType());
            System.out.println("是否成功: " + response.isSuccess());
            System.out.println("响应体长度: " + response.getContentLength());

            // 只打印部分响应体
            if (response.getBody() != null && response.getBody().length() > 200) {
                System.out.println("响应体: " + response.getBody().substring(0, 200) + "...");
            } else {
                System.out.println("响应体: " + response.getBody());
            }
        } catch (Exception e) {
            System.err.println("GET请求失败: " + e.getMessage());
        } finally {
            client.close();
        }

        System.out.println();
    }

    /**
     * GET请求解析对象示例
     */
    public static void getObjectExample() {
        System.out.println("3. GET请求解析对象示例");
        System.out.println("=" + "=".repeat(50));

        RestClient client = new RestClient();

        try {
            String url = "https://httpbin.org/user-agent";
            HttpResponse<Map<String, Object>> response = client.get(url, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {});

            System.out.println("请求URL: " + url);
            System.out.println("状态码: " + response.getStatusCode());
            System.out.println("解析结果: " + response.getData());

            // 另一个示例，使用自定义对象
            url = "https://httpbin.org/uuid";
            Map<String, Object> uuidResponse = client.get(url, java.util.Map.class).getData();
            if (uuidResponse != null) {
                System.out.println("UUID: " + uuidResponse.get("uuid"));
            }

        } catch (Exception e) {
            System.err.println("GET对象请求失败: " + e.getMessage());
        } finally {
            client.close();
        }

        System.out.println();
    }

    /**
     * GET请求解析列表示例
     */
    public static void getListExample() {
        System.out.println("4. GET请求解析列表示例");
        System.out.println("=" + "=".repeat(50));

        RestClient client = new RestClient();

        try {
            // 模拟返回列表的API
            String url = "https://httpbin.org/json";

            // 这里使用自定义TypeReference来解析复杂的JSON结构
            HttpResponse<Map<String, Object>> response = client.get(url,
                new com.fasterxml.jackson.core.type.TypeReference<java.util.Map<String, Object>>() {});

            System.out.println("请求URL: " + url);
            System.out.println("状态码: " + response.getStatusCode());
            System.out.println("解析结果类型: " + response.getData().getClass().getSimpleName());
            System.out.println("解析结果: " + JsonUtils.toPrettyJson(response.getData()));

        } catch (Exception e) {
            System.err.println("GET列表请求失败: " + e.getMessage());
        } finally {
            client.close();
        }

        System.out.println();
    }

    /**
     * POST请求示例
     */
    public static void postExample() {
        System.out.println("5. POST请求示例");
        System.out.println("=" + "=".repeat(50));

        RestClient client = new RestClient();

        try {
            String url = "https://httpbin.org/post";

            // 创建要发送的用户对象
            User user = User.builder()
                    .id(1L)
                    .username("testuser")
                    .email("test@example.com")
                    .name("测试用户")
                    .age(25)
                    .active(true)
                    .createdAt(LocalDateTime.now())
                    .build();

            // 发送POST请求
            HttpResponse<Map<String, Object>> response = client.post(url, user, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {});

            System.out.println("请求URL: " + url);
            System.out.println("请求体: " + JsonUtils.toPrettyJson(user));
            System.out.println("状态码: " + response.getStatusCode());
            System.out.println("响应时间: " + response.getResponseTime() + "ms");

            // 解析返回的JSON数据
            Map<String, Object> data = response.getData();
            if (data != null && data.get("json") instanceof Map) {
                System.out.println("服务器接收到的数据: " + JsonUtils.toPrettyJson(data.get("json")));
            }

        } catch (Exception e) {
            System.err.println("POST请求失败: " + e.getMessage());
        } finally {
            client.close();
        }

        System.out.println();
    }

    /**
     * PUT请求示例
     */
    public static void putExample() {
        System.out.println("6. PUT请求示例");
        System.out.println("=" + "=".repeat(50));

        RestClient client = new RestClient();

        try {
            String url = "https://httpbin.org/put";

            // 创建更新数据
            Map<String, Object> updateData = new HashMap<>();
            updateData.put("id", 1);
            updateData.put("name", "更新后的用户");
            updateData.put("email", "updated@example.com");
            updateData.put("updatedAt", LocalDateTime.now());

            // 发送PUT请求
            HttpResponse<Map<String, Object>> response = client.put(url, updateData, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {});

            System.out.println("请求URL: " + url);
            System.out.println("请求数据: " + JsonUtils.toPrettyJson(updateData));
            System.out.println("状态码: " + response.getStatusCode());
            System.out.println("响应时间: " + response.getResponseTime() + "ms");

        } catch (Exception e) {
            System.err.println("PUT请求失败: " + e.getMessage());
        } finally {
            client.close();
        }

        System.out.println();
    }

    /**
     * DELETE请求示例
     */
    public static void deleteExample() {
        System.out.println("7. DELETE请求示例");
        System.out.println("=" + "=".repeat(50));

        RestClient client = new RestClient();

        try {
            String url = "https://httpbin.org/delete";

            // 发送DELETE请求
            HttpResponse<Map<String, Object>> response = client.delete(url, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {});

            System.out.println("请求URL: " + url);
            System.out.println("状态码: " + response.getStatusCode());
            System.out.println("响应时间: " + response.getResponseTime() + "ms");

            Map<String, Object> data = response.getData();
            if (data != null) {
                System.out.println("删除结果: " + JsonUtils.toPrettyJson(data));
            }

        } catch (Exception e) {
            System.err.println("DELETE请求失败: " + e.getMessage());
        } finally {
            client.close();
        }

        System.out.println();
    }

    /**
     * 自定义请求头示例
     */
    public static void customHeadersExample() {
        System.out.println("8. 自定义请求头示例");
        System.out.println("=" + "=".repeat(50));

        RestClient client = new RestClient();

        try {
            String url = "https://httpbin.org/headers";

            // 设置自定义请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("X-Custom-Header", "custom-value");
            headers.put("Authorization", "Bearer token123");
            headers.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");

            // 发送带有自定义请求头的GET请求
            HttpResponse<Map<String, Object>> response = client.get(url, headers, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {});

            System.out.println("请求URL: " + url);
            System.out.println("自定义请求头: " + headers);
            System.out.println("状态码: " + response.getStatusCode());

            Map<String, Object> data = response.getData();
            if (data != null && data.containsKey("headers")) {
                System.out.println("服务器接收到的请求头: " + JsonUtils.toPrettyJson(data.get("headers")));
            }

        } catch (Exception e) {
            System.err.println("自定义请求头请求失败: " + e.getMessage());
        } finally {
            client.close();
        }

        System.out.println();
    }

    /**
     * 错误处理示例
     */
    public static void errorHandlingExample() {
        System.out.println("9. 错误处理示例");
        System.out.println("=" + "=".repeat(50));

        RestClient client = new RestClient();

        try {
            // 请求一个不存在的URL，测试404错误
            String url = "https://httpbin.org/status/404";
            HttpResponse<String> response = client.get(url);

            System.out.println("请求URL: " + url);
            System.out.println("状态码: " + response.getStatusCode());
            System.out.println("是否成功: " + response.isSuccess());
            System.out.println("是否客户端错误: " + response.isClientError());
            System.out.println("是否服务器错误: " + response.isServerError());

            // 测试500错误
            url = "https://httpbin.org/status/500";
            response = client.get(url);

            System.out.println("\n请求URL: " + url);
            System.out.println("状态码: " + response.getStatusCode());
            System.out.println("是否成功: " + response.isSuccess());
            System.out.println("是否客户端错误: " + response.isClientError());
            System.out.println("是否服务器错误: " + response.isServerError());

        } catch (Exception e) {
            System.err.println("错误处理测试失败: " + e.getMessage());
        } finally {
            client.close();
        }

        System.out.println();
    }

    /**
     * JSON工具类示例
     */
    public static void jsonUtilsExample() {
        System.out.println("10. JSON工具类示例");
        System.out.println("=" + "=".repeat(50));

        // 创建对象
        User user = User.builder()
                .id(100L)
                .username("jsonuser")
                .email("json@example.com")
                .name("JSON测试用户")
                .age(30)
                .active(true)
                .build();

        // 对象转JSON
        String json = JsonUtils.toJson(user);
        System.out.println("对象转JSON: " + json);

        // 格式化JSON
        String prettyJson = JsonUtils.toPrettyJson(user);
        System.out.println("\n格式化JSON:\n" + prettyJson);

        // JSON转对象
        User parsedUser = JsonUtils.fromJson(json, User.class);
        System.out.println("\nJSON转对象: " + parsedUser);

        // JSON转Map
        Map<String, Object> userMap = JsonUtils.fromJsonToMap(json);
        System.out.println("\nJSON转Map: " + userMap);

        // 对象转Map
        Map<String, Object> objectMap = JsonUtils.objectToMap(user);
        System.out.println("\n对象转Map: " + objectMap);

        // Map转对象
        User mapUser = JsonUtils.mapToObject(objectMap, User.class);
        System.out.println("\nMap转对象: " + mapUser);

        // JSON有效性验证
        boolean isValid = JsonUtils.isValidJson(json);
        System.out.println("\nJSON有效性验证: " + isValid);

        // 美化JSON
        String uglyJson = "{\"name\":\"test\",\"age\":25}";
        String beautified = JsonUtils.prettyJson(uglyJson);
        System.out.println("\n美化前: " + uglyJson);
        System.out.println("美化后: " + beautified);

        System.out.println();
    }
}